import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { IncidentService } from '../incident.service';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { DialogService } from 'app/shared/dialog';
import { ToolbarComponent } from 'app/public/toolbar/toolbar.component';
import { PublicService } from 'app/public/public.service';
import { SELECT_OPTIONS } from 'app/app.constants';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import * as moment from 'moment';
import { BullySubjectService } from 'app/shared/service';
import { differenceInCalendarDays } from 'date-fns';
import { AuthService } from 'app/auth/auth.service';

@Component({
    selector: 'itmp-incident-record-list',
    templateUrl: './incident-record-list.component.html',
    styleUrls: ['./incident-record-list.component.css']
})
export class IncidentRecordListComponent implements OnInit {
    @ViewChild(ToolbarComponent) toolbarCom: ToolbarComponent;
    @Output() changeTabPage = new EventEmitter();
    @Output() isIrSelected = new EventEmitter();
    @Input() accessButton;

    selectedItem = null;

    queryCondition = {
        ir_ID: null,
        type: null,
        start_Time: null,
        end_Time: null,
        zone_ID: null,
        road_Name: null,
        source: null,
        veri_State: null
    };
    queryAlertId = null;
    pagination = {
        totalEle: 0,
        currentPage: 1,
        currentSize: 10,
        pageSize: 10
    };
    isEditable = false;
    editingItem = null;
    listOfData = [];
    statusList: any;
    // typeList = ['', 'Accident', 'Road Works', 'Obstacle', '', 'Bad Weather', 'vehicles breakdown', 'ReverseFlow', 'Fire', 'Congestion'];
    typeList: any;
    // lane_blockages = ['arrow-up.png', 'cross.png'];
    laneBlockageObj = { '1': 'arrow-up.png', '3': 'cross.png' };
    sourceList: any;
    sourceSelectList = null;
    statusSelectList = null;
    renderHeader = null;
    toolbarList = [
        { className: 'icon-CCTV' },
        { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' },
        { className: 'icon-xiazai' }
    ];
    irType: any;
    irTypeSelect = null;
    dateRange = [];
    clearDateRange = [];
    queryStartTime = null;
    queryEndTime = null;
    queryClearStartTime = null;
    queryClearEndTime = null;
    queryData = null;
    now: any;
    zoneIdList = [];
    confirmModal: NzModalRef; // For testing by now
    // subscription = new Subscription();
    private searchText$ = new Subject<any>();

    // ackButton = false;
    // ignoreButton = false;
    // exportButton = false;
    // gisButton = false;
    // printButton = false;
    // monitorButton = false;
    // createButton = false;
    // editButton = false;
    showTable = false;

    constructor(
        private incidentService: IncidentService,
        private message: NzMessageService,
        private dialog: DialogService,
        private pub: PublicService,
        private bully: BullySubjectService,
        private authService: AuthService
    ) {}

    ngOnInit() {
        const res1 = this.pub.getSelectOptionsList(SELECT_OPTIONS.INCIDENT_SOURCE, true);
        this.sourceSelectList = res1.data;
        this.sourceList = res1.object;
        if (localStorage.getItem('itmp_lang') === 'vi') {
            this.sourceSelectList.forEach(site => {
                site.displayName = site.vietName;
            });
        } else {
            this.sourceSelectList.forEach(site => {
                site.displayName = site.name;
            });
        }
        const res2 = this.pub.getSelectOptionsList(SELECT_OPTIONS.INCIDENT_STATUS, true);
        this.statusSelectList = res2.data;
        this.statusList = res2.object;
        const res3 = this.pub.getSelectOptionsList(SELECT_OPTIONS.INCIDENT_TYPE, true);
        this.irType = res3.data;
        this.typeList = res3.object;
        this.getHeader();
        this.showTable = true;
        // this.getAllList();
        this.bully.zoneListBehavior.subscribe(res => {
            this.zoneIdList = res['selectZoneList'] ? res['selectZoneList'] : [];
            this.getAllList();
        });
        this._getNow();
        this.searchText$
            .asObservable()
            .pipe(debounceTime(1000), distinctUntilChanged())
            .subscribe(_res => this.getAllList());
    }

    getHeader() {
        this.renderHeader = this.incidentService.renderHeader(this.sourceSelectList, this.statusSelectList);
    }

    _getNow() {
        this.now = new Date().getTime();
    }

    getAllList() {
        const pageParam = {
            pageNo: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        const start_Time = {
            startTime: this.queryStartTime,
            endTime: this.queryEndTime
        };
        const e_Time = {
            startTime: this.queryClearStartTime,
            endTime: this.queryClearEndTime
        };
        this.queryData = this.incidentService.formIncidentRecordListData(
            this.renderHeader,
            start_Time,
            e_Time,
            this.irTypeSelect,
            pageParam,
            this.zoneIdList
        );
        const query = this.incidentService.getIncidentRecordList(this.queryData);
        query.subscribe(
            (res: any) => {
                if (res.messagecode === '000000') {
                    this.listOfData = res.data.content;
                    this.pagination.totalEle = res.data.totolElements;
                    this.pagination.currentSize = res.data.numberOfElements;
                    this.listOfData.forEach(element => {
                        if (element.lane_Blockage != null) {
                            const strSplit = element.lane_Blockage.split('');
                            element.laneBlockage = strSplit;
                        }
                    });
                } else {
                    this.message.create('warning', 'Request failed.');
                    this.listOfData = [];
                }
            },
            (error: any) => {}
        );
    }

    showDetail(item): void {
        this.editingItem = item.ir_ID;
        this.isEditable = true;
        this.isIrSelected.emit(item);
        this.selectedItem = item;
        // const bully: Bully = {
        //     type: 'selectItem',
        //     data: item
        // };
        // this.bully.setSubject(bully);
    }

    addOrEdit(flag): void {
        if (flag === 'add') {
            this.isEditable = false;
            this.editingItem = null;
            this.changeTabPage.emit(null);
        } else if (flag === 'edit') {
            if (this.selectedItem === null) {
                this.message.create('warning', 'Please select a record.');
            } else {
                if (!this.authService.isUserZoneChecked(this.selectedItem.zone_ID)) {
                    return;
                }
                this.changeTabPage.emit(this.selectedItem);
                this.selectedItem = null;
                this.editingItem = null;
                this.isEditable = false;
            }
        }
    }

    delete(): void {
        this.comfirm();
        if (this.editingItem !== null) {
            // this.modal.confirm({
            //     nzTitle: '<p>Do you Want to delete record ' + this.editingItem + '?</p>',
            //     nzOnOk: () => this.message.create('success', 'Success')
            // });
            this.dialog
                .confirm({
                    title: 'Home.Home.Delete_Confirm',
                    content: 'Do you Want to delete record ' + this.editingItem + '?',
                    buttonOkTxt: 'Yes',
                    buttonCancelTxt: 'Cancel'
                })
                .subscribe(res => {});
        } else {
            this.message.create('warning', 'Please select a record.');
        }
    }

    public refresh(): void {
        this.getHeader();
        this.irTypeSelect = null;
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.dateRange = [];
        this.clearDateRange = [];
        this.queryStartTime = null;
        this.queryEndTime = null;
        this.queryClearStartTime = null;
        this.queryClearEndTime = null;
        this.queryAlertId = null;
        // this.filterSearch();
        this.getAllList();
    }

    // page change
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getAllList();
    }

    onSizeChange(e) {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = e;
        this.getAllList();
    }

    comfirm() {
        this.dialog
            .confirm({
                title: 'Home.Home.Delete_Confirm',
                content: '是否删除',
                buttonOkTxt: 'Save',
                buttonCancelTxt: 'Cancel'
            })
            .subscribe(res => {});
    }

    filterSearch() {
        const params = JSON.stringify(this.renderHeader);
        this.searchText$.next(params);
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
    }

    public irTypeSearch() {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getAllList();
    }

    onChange(result: Date): void {
        this.queryStartTime = new Date(moment(result[0]).format('YYYY-MM-DD 00:00:00')).getTime();
        this.queryEndTime = new Date(moment(result[1]).format('YYYY-MM-DD 23:59:59')).getTime();
        if (this.dateRange.length === 0) {
            this.queryStartTime = null;
            this.queryEndTime = null;
        }
        this.getAllList();
    }

    clearTimeOnChange(result: Date): void {
        this.queryClearStartTime = new Date(moment(result[0]).format('YYYY-MM-DD 00:00:00')).getTime();
        this.queryClearEndTime = new Date(moment(result[1]).format('YYYY-MM-DD 23:59:59')).getTime();
        if (this.clearDateRange.length === 0) {
            this.queryClearStartTime = null;
            this.queryClearEndTime = null;
        }
        this.getAllList();
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };
}
